package com.lifeCicle.validators;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.el.ELContext;
import javax.el.ExpressionFactory;

import javax.el.ValueExpression;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class emailValidators implements Validator {
    public emailValidators() {
        super();
    }

    public void validate(FacesContext facesContext, UIComponent uIComponent,Object object) throws ValidatorException {
       String regex = "^\\w+([\\.]?\\w+)@\\w+([\\.]?\\w+)(\\.\\w{2,3})+$";
       //{pageFlowScope.email}
        Object o;
        o = this.evaluarEL("#{pageFlowScope.email}");
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(object.toString());
        if(!matcher.matches()){
           // throw new ValidatorException(new FacesMessage("Email invalido"));
           FacesMessage facesMessage = new  FacesMessage();
           facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
           facesMessage.setDetail("Email invalido");
           facesMessage.setSummary("emailValidator");
           facesContext.getCurrentInstance().addMessage("f1:email",facesMessage);
        }
    }
    
    public static Object evaluarEL(String el) {
           try {
               FacesContext facesContext = FacesContext.getCurrentInstance();
               Application app = facesContext.getApplication();
               ExpressionFactory elFactory = app.getExpressionFactory();
               ELContext elContext = facesContext.getELContext();
               ValueExpression valueExp =
                   elFactory.createValueExpression(elContext, el, Object.class);
               return valueExp.getValue(elContext);
           } catch (Exception e) {
                     e.printStackTrace();
             
               return null;
           }
       }
}
